﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Text;
using System.Security.Cryptography;
using System.Text;
using System.Xml;

namespace spbtzb
{
    /// <summary>
    /// Summary description for AuthenCtr
    /// </summary>
    public class AuthenCtr
    {
	    private AuthenCtr()
	    {
		    //
		    // TODO: Add constructor logic here
		    //
	    }
            
        ///<summary>
        /// Html Encode
        ///</summary>
        ///<param name = "str">string </param>
        ///<returns>string</returns>
        ///
        public static string Encode(string str)
        {
            str = str.Replace("&", "&amp;");
            str = str.Replace("'", "''");
            str = str.Replace("\"", "&quot;");
            str = str.Replace(" ", "&nbsp;");
            str = str.Replace("<", "&lt;");
            str = str.Replace(">", "&gt;");
            str = str.Replace("\n", "<br/>");

            return str;
     
        }

        ///<summary>
        ///decode
        ///</summary>
        ///<param name = "str">string </param>
        ///<returns>string</returns>
        ///
        public static string Decode(string str)
        {
            str = str.Replace("<br/>", "\n");
            str = str.Replace("&gt;", ">");
            str = str.Replace("&lt;", "<");
            str = str.Replace("&nbsp;", " ");
            str = str.Replace("&quot;", "\"");
            return str;
        }

        /// <summary>
        /// 判断是否为整数
        /// </summary>
        /// <param name="strInput"></param>
        /// <returns></returns>
        public static Boolean IsInt(String strInput)
        {
            try
            {
                Convert.ToInt32(strInput);
                return true;
            }
            catch (FormatException fe)
            {
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }

        }


        ///<summary>
        /// Encrypting string 
        ///</summary>
        ///<param name = "Password">string </param>
        ///<returns>string</returns>
        ///
        public static string Encrypt(string Password)
        {
            string str = "";

            // 创建身份验证票
            // 使用 cookie 名和过期信息初始化 FormsAuthenticationTicket 
            // 类的新实例
            FormsAuthenticationTicket ticket = 
                new FormsAuthenticationTicket(Password, true, 2);
            
            /* 
             * Encrypt(): 创建一个字符串，其中包含适用于HTTP Cookie的 
             * 加密的Forms身份验证票证 
             */ 
            str = FormsAuthentication.Encrypt(ticket).ToString();
            return str;

        }

        ///<summary>
        /// Encrypting string 
        ///</summary>
        ///<param name = "Password">string </param>
        ///<param name = "Format">format, 0 is SHA1, 1 is MD5</param>
        ///<returns>string</returns>
        ///
        public static string Encrypt(string Password, int Format)
        {
            string str = "";
            switch(Format)
            {

               /*
                * HashPasswordForStoringInConfigFile():
                * 根据指定的密码和哈希算法生成一个适合于
                * 存储在配置文件中的哈希密码。 
                */ 
                case 0:
                    str = 
       FormsAuthentication.HashPasswordForStoringInConfigFile(Password, "SHA1");
                    break;
                case 1:
                    str =
       FormsAuthentication.HashPasswordForStoringInConfigFile(Password, "MD5");
                    break;
                default:
                    str = 
       FormsAuthentication.HashPasswordForStoringInConfigFile(Password, "SHA1");
                    break;
            }
            return str;

        }

        
        ///<summary>
        /// Descript string 
        ///</summary>
        ///<param name = "Password">encrypted string</param>
        ///<returns>string</returns>
        ///
        public static string Decrypt(string Password)
        {
            string str = "";

            // 首先，Decrypt 函数返回一个 Ticket
            str = FormsAuthentication.Decrypt(Password).Name.ToString();

            return str;

        }


        ///<summary>
        /// Encrypt Cookie 
        ///</summary>
        ///<param name = "str"> Target cookie string</param>
        /// <param name="type">int</param>
        ///<returns>string</returns>
        ///  
        public static string EncryptCookie(string strCookie, int type)
        {
            string str = En(strCookie, type);
            StringBuilder sb = new StringBuilder();
            foreach (char a in str)
            {
                //sb.Append(Convert.ToString(a, 16).PadLeft(4, "0"));
                sb.Append(Convert.ToString(a, 16).PadLeft(4, '0'));
            }

            return sb.ToString();
        }

        /// <summary>
        /// Decrypt Cookie
        /// </summary>
        /// <param name="str">Target cookie string</param>
        /// <returns></returns>
        /// 
        public static string DecryptCookie(string strCookie, int type)
        {
            StringBuilder sb = new StringBuilder();
            string[] strarr = new String[255];
            int i, j, count = strCookie.Length / 4;
            string strTmp;

            for (i = 0; i < count; i++)
            {
                for (j = 0; j < 4; j++)
                {
                    sb.Append(strCookie.Substring(i * 4 + j, 1));

                }
                strarr[i] = sb.ToString();
                sb.Remove(0, sb.Length);
            }

            for (i = 0; i < count; i++)
            {
                // 
                //  strTmp = uint.Parse(strarr[i],
                //      System.Globalization.NumberStyles.AllowHexSpecifier.ToString("D"));

                strTmp = uint.Parse(strarr[i], System.Globalization.NumberStyles.AllowHexSpecifier).ToString("D");
                char ch = (char)uint.Parse(strTmp);
                sb.Append(ch);
     
            }

            return De(sb.ToString(), type);
        }


        ///<summary>
        /// Encrypt  
        ///</summary>
        ///<param name = "str"> Target cookie string</param>
        /// <param name="type">int</param>
        ///<returns>string</returns>
        /// 
        private static string En(string strCookie, int type)
        {
            string str;
            if (type % 2 == 0)
            {
                str = Transform1(strCookie);
            }
            else
            {
                str = Transform3(strCookie);
            }

            str = Transform2(strCookie);
            return str;
        }

        private static string De(string strCookie, int type)
        {
            string str;

            if (type % 2 == 0)
            {
                str = DeTransform1(strCookie);
            }
            else
            {
                str = DeTransform3(strCookie);
            }

            str = Transform2(strCookie);
            return str;
        }



        /// <summary>
        /// reverse 颠倒字符串
        /// </summary>
        /// <param name="str">string</param>
        /// <returns>reversed string</returns>
        public static string Reverse(string str)
        {
            int i;
            StringBuilder sb = new StringBuilder();

            for (i = str.Length - 1; i >= 0; i--)
            {
                sb.Append(str[i]);
            }

            return sb.ToString();
        }



        /// <summary>
        /// method1
        /// </summary>
        /// <param name="str">string</param>
        /// <returns>encrypted string</returns>
        public static string Transform3(string str)
        {
            int i = 0;
            StringBuilder sb = new StringBuilder();

            foreach (char a in str)
            {
                switch (i % 6)
                {
                    case 0:
                        sb.Append((char)(a + 3));
                        break;
                    case 1:
                        sb.Append((char)(a + 6));
                        break;
                    case 2:
                        sb.Append((char)(a + 8));
                        break;
                    case 3:
                        sb.Append((char)(a + 7));
                        break;
                    case 4:
                        sb.Append((char)(a + 5));
                        break;
                    case 5:
                        sb.Append((char)(a + 2));
                        break;
                }
                i++;
            }
            return sb.ToString();
        }

        /// <summary>
        /// method1(什么意思哦)
        /// </summary>
        /// <param name="str">string</param>
        /// <returns>encrypted string</returns>
        public static string Transform2(string str)
        {
          
            uint j = 0;
            StringBuilder sb = new StringBuilder();

            str = Reverse(str);

            foreach (char a in str)
            {
                j = a; // ?
                if (j > 255)
                {
                    // 右移运算符 (>>) 将第一个操作数向右移动第二个操作数所指定的位数。
                    j = (uint)((a >> 8) + ((a & 0x0ff) << 8));
                }
                else
                {
                    j = (uint)((a >> 4) + ((a & 0x0f) << 4));
     
                }

                sb.Append((char)j);

            }

            return sb.ToString();
        }


        /// <summary>
        /// method1(什么意思哦)
        /// </summary>
        /// <param name="str">string</param>
        /// <returns>encrypted string</returns>
        public static string Transform1(string str)
        {
            int i = 0;
            StringBuilder sb = new StringBuilder();

            foreach (char a in str)
            {
                switch (i % 6)
                {
                    case 0:
                        sb.Append((char)(a + 1));
                        break;
                    case 1:
                        sb.Append((char)(a + 5));
                        break;
                    case 2:
                        sb.Append((char)(a + 7));
                        break;
                    case 3:
                        sb.Append((char)(a + 2));
                        break;
                    case 4:
                        sb.Append((char)(a + 4));
                        break;
                    case 5:
                        sb.Append((char)(a + 9));
                        break;
                }

                i++;
            }

            return sb.ToString();
        }




        /// <summary>
        /// methods 1
        /// </summary>
        /// <param name="str">string</param>
        /// <returns>decrypted string</returns>
        /// 
        public static string DeTransform1(string str)
        {
            int i = 0;
            StringBuilder sb = new StringBuilder();

            foreach (char a in str)
            {
                switch (i % 6)
                {
                    case 0:
                        sb.Append((char)(a - 1));
                        break;
                    case 1:
                        sb.Append((char)(a - 5));
                        break;
                    case 2:
                        sb.Append((char)(a - 7));
                        break;
                    case 3:
                        sb.Append((char)(a - 2));
                        break;
                    case 4:
                        sb.Append((char)(a - 4));
                        break;
                    case 5:
                        sb.Append((char)(a - 9));
                        break;
     
                }

                ++i;
            }

            return sb.ToString();
        }


        /// <summary>
        /// methods 1
        /// </summary>
        /// <param name="str">string</param>
        /// <returns>decrypted string</returns>
        public static string DeTransform3(string str)
        {
            int i = 0;
            StringBuilder sb = new StringBuilder();

            foreach (char a in str)
            {
                switch (i % 6)
                {
                    case 0:
                        sb.Append((char)(a - 3));
                        break;
                    case 1:
                        sb.Append((char)(a - 6));
                        break;
                    case 2:
                        sb.Append((char)(a - 8));
                        break;
                    case 3:
                        sb.Append((char)(a - 7));
                        break;
                    case 4:
                        sb.Append((char)(a - 5));
                        break;
                    case 5:
                        sb.Append((char)(a - 2));
                        break;
                }
                i++;
            }

            return sb.ToString();
        }


        // Hash an input string and return the hash as
        // a 32 character hexadecimal string.
        public static string getMd5Hash(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

        // Verify a hash against a string.
        public static bool verifyMd5Hash(string input, string hash)
        {
            // Hash the input.
            string hashOfInput = getMd5Hash(input);

            // Create a StringComparer an comare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }




        /// <summary> 
        /// 修改web.config文件appSettings配置节中的Add里的value属性 
        /// </summary> 
        /// <remarks> 
        /// 注意，调用该函数后，会使整个Web Application重启，导致当前所有的会话丢失 
        /// </remarks> 
        /// <param name="key">要修改的键key</param> 
        /// <param name="strValue">修改后的value</param> 
        /// <exception cref="">找不到相关的键</exception> 
        /// <exception cref="">权限不够，无法保存到web.config文件中</exception> 
        public static void Modify(string key, string strValue)
        {
            string XPath = "/configuration/appSettings/add[@key='?']";
            XmlDocument domWebConfig = new XmlDocument();
            domWebConfig.Load((HttpContext.Current.Server.MapPath("~/web.config")));
            XmlNode addKey = domWebConfig.SelectSingleNode((XPath.Replace("?", key)));
            if (addKey == null)
            {
                throw new ArgumentException("没有找到<add key='" + key + "' value=.../>的配置节");
            }
            addKey.Attributes["value"].InnerText = strValue;
            domWebConfig.Save((HttpContext.Current.Server.MapPath("~/web.config")));
        }


        public static void ModifyEx(String[] strkeys, String[] strValues)
        {
            if (strkeys.Length != strValues.Length) { throw new ArgumentException("参数个数不一致"); }
            Configuration config =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
            for (int i = 0; i < strkeys.Length; i++)
            {
                appSection.Settings[(strkeys[i])].Value = strValues[i];
            }
            config.Save(ConfigurationSaveMode.Modified, true);
        }

    }//cs


}// ns
